import { hasOwnProperty, isEqual, isObject } from "../shared/utils";
import { reactive } from "./reactive";

const get = createGetter(),
  set = createSetter();
function createGetter() {
  return (target, key, receiver) => {
    const res = Reflect.get(target, key, receiver);
    console.log('响应式获取' + key + ':' + res);
    if (isObject(target)) {
        reactive(target)
    }
    return res
  };
}

function createSetter() {
  return (target, key, value, receiver) => {
    const isKeyExist = hasOwnProperty(target, key);
    const oldValue = target[key];
    const res = Reflect.set(target, key, value, receiver);
    if (!isKeyExist) {
        console.log('响应式新增' + key + ':' + value);
    } else if (!isEqual(oldValue, value)) {
        console.log('响应式修改' + key + ':' + value);
    }
    return res
  };
}

const mutableHandler = {
  get,
  set,
};

export { mutableHandler };
